<?php

//app返回的消息
function appMessage($code,$message,$result=''){
    header("Content-type: application/json");
    $result = [
      "code"   => $code,
      "msg"    => $message,
      "data"   => $result
    ];
    echo json_encode($result);
    die;
}

function sendToSms($mobile,$type=1){
    $url = "http://101.200.29.88:8082/SendMT/SendMessage";
    $code	 = returnNum(6);
    switch ($type){
        case 1:
            $content = "【小鹿快淘】您的验证码是".$code."，10分钟内有效。如非本人操作，请忽略此短信。";
            $msg = "手机登录注册";
            break;
        default:
            return false;
            break;

    }
    //泰迪熊短信发送
    $param = [
        "CorpID"  => "zhulutianxia",
        "Pwd"      =>  "zl@985211",
        "Mobile"  => $mobile,
        "Content" => $content,
    ];
    $res = curl_request($url,$param,1);
    //返回结果处理
    $result = explode(",",$res);
    $insertData = ["mobile"=>$mobile,"code"=>$code,"msg"=>$msg,"type"=>$type,"addtime"=>time()];
    if ($result[0]=="03"){
        $insertData["status"] = 1;
        DB::table("send_sms")->insert($insertData);
        return true;
    }elseif ($result[0]=="00"){
        return true;
    }else{

        $insertData["status"] = 4;
        DB::table("send_sms")->insert($insertData);
        return false;
    }
}

/**
 * 生成验证码
 * @param number $number
 * @return number
 */
function returnNum($number=8){
    $int = rand(1,9);
    for($i=1;$i<=$number-1;$i++){
        $int .= rand(0,9);
    }
    return $int;
}

/**
 * [curl_request CURL请求]
 * @param  [type]  $url   [url]
 * @param  [type]  $data  [data]
 * @param  integer $post  [是否post发送]
 * @param  boolean $https [是否https]
 * @return [type]         [description]
 */
function curl_request($url, $data = null, $post = false, $https = false)
{
    if(is_array($data)) $data = http_build_query($data);
    //初始化curl
    $ch = curl_init();  // 启动一个CURL会话
    $this_header = array("content-type: application/x-www-form-urlencoded;charset=UTF-8");
    //参数设置
    curl_setopt($ch, CURLOPT_HTTPHEADER,$this_header);
    curl_setopt($ch, CURLOPT_URL, $url);    // 要访问的地址
    curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);   // 模拟用户使用的浏览器
    curl_setopt($ch, CURLOPT_REFERER, '');   // 设置Referer
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);    // 获取的信息以文件流的形式返回
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, $https);   // 对认证证书来源的检查
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);   // 设置超时限制防止死循环
    if ($post){
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
        curl_setopt($ch, CURLOPT_POST, true);   // 发送一个常规的Post请求
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);  // Post提交的数据包
    }
    $json = curl_exec($ch);
    curl_close($ch);
    return $json;
}

/**
 * 生成用户 token (保存到mysql)
 * @param $userInfo
 * @param $deviceType
 * @return string 用户 token
 */
function generate_user_token($userInfo, $deviceType, $isAdmin = 0)
{
    $key = "gx3xzFUD0Sq3WX2SqzjpSkiYdZnKfu11sW2QdoReUkcpTuBfQB";
    $userId = $userInfo['id'];
    $currentTime = time();
    $expireTime = $currentTime + 24 * 3600 * 2;
    $data = [
      "userId" => $userId,
      "mobile" => $userInfo["phone"],
      "time"   => $currentTime,
      "uuid"   => $userInfo["uuid"]
    ];
    ksort($data);
    $string = '';
    foreach ($data as $key=>$value){
        $string .= $key."=".$value."&";
    }
    $tmp = strtoupper($string).$key;
    $token = md5($tmp);
    $result = DB::table("members")->where('id',$userId)->update([
        'remember_token' => $token,
        'expire_time'    => $expireTime,
    ]);
    if (empty($result)) {
        return false;
    }
    return $token;
}

function checkToken($token){
    $where = ['remember_token'=>$token];
    //$userInfo = DB::table("members")->where($where)->first(['id','name','phone','avatar','remember_token','expire_time']);
    //$userInfo = json_decode(json_encode($userInfo), true);
    $userInfo=\App\Models\Member::query()
        ->where($where)
        ->select('id','name','phone','avatar','remember_token','expire_time')
        ->first();
    if (empty($userInfo)){
        appMessage('1','未找到该用户');
    }else{
        //if (time()>$userInfo['expire_time']) appMessage('11','该token已过期');
        $userInfo=$userInfo->toArray();
        return $userInfo;
    }
}
function getMemberIdByToken($token){
    $where = ['remember_token'=>$token];
    $userInfo = DB::table("members")->where($where)->first(['id']);
    return $userInfo;
}
function timer($dateTime){
    $t = strtotime($dateTime)-time();//单位"秒"
    $arr = [];
    $str='';
    $day = intval($t/86400);//天
    $arr['day'] = $day;
    if($day>0)
        $str.=$day.'天';
    $hour = intval((($t/86400)-$day)*24);//小时
    $arr['hour'] = $hour;
    if($day>0){
        $str.=$hour.'小时';
    }else{
        if($hour>0)
            $str.=$hour.'小时';
    }
    $minute = intval( (((($t/86400)-$day)*24)-$hour)*60 );//分钟
    $arr['minute'] = $minute;
    if($day>0 || $hour>0){
        $str.=$minute.'分钟';
    }else{
        if($minute>0)
            $str.=$minute.'分钟';
    }
    $second = intval(((((((($t/86400)-$day)*24)-$hour)*60)-$minute)*60));//秒
    $arr['second'] = $second;
    $str.=$second.'秒';
    $arr['str']=$str;
    return $arr;
}

